package com.echo.im.infrastructure.exception;


import com.echo.im.common.exception.GlobalException;
import com.echo.im.common.result.Result;
import com.echo.im.common.result.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.UndeclaredThrowableException;


/**
 * @author echo
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<Void> handleException(Exception e) {
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            // token过期是正常情况,不打印
            if(!ex.getCode().equals(ResultEnum.INVALID_TOKEN.getCode())){
                log.error("全局异常捕获:msg:{},log:{},{}", ex.getMessage(), e);
            }
            return Result.fail(ex.getCode(), ex.getMessage());
        } else if (e instanceof UndeclaredThrowableException) {
            GlobalException ex = (GlobalException) e.getCause();
            log.error("全局异常捕获:msg:{},log:{},{}", ex.getMessage(), e);
            return Result.fail(ex.getCode(), ex.getMessage());
        } else {
            log.error("全局异常捕获:msg:{},{}", e.getMessage(), e);
            return Result.error();
        }
    }

}
